/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.generator.GetHardwareIdFailedException;
import com.koron.common.generator.InvalidSystemClockException;
import com.koron.common.stub.Port;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.service.impl.HiddenDangerDiscoveryServiceImpl;
import com.koron.hiddendanger.service.impl.HiddenDangerRectificationServiceImpl;
import com.koron.risk.util.GridHelpUtils;
import com.koron.scene.domain.DeviceHiddenDanger;
import com.koron.scene.domain.TeamHandover;
import com.koron.scene.domain.TeamHandoverRelation;
import com.koron.scene.mapper.TeamHandoverMapper;
import com.koron.scene.service.api.TeamHandoverService;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeamHandoverServiceImpl implements TeamHandoverService, AfterApprovalService, InitializingBean {

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    private final static  Logger logger = LoggerFactory.getLogger(TeamHandoverServiceImpl.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private GridHelpUtils helpUtils;

    @Autowired
    private Util util;

    @Autowired
    private IndicationItemsService indicationItemsService;

    @Autowired
    private HiddenDangerDiscoveryService hiddenDangerService;

    @Autowired
    private HiddenDangerDiscoveryService dangerDiscoveryService;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private HiddenDangerDiscoveryService discoveryService;

    @Override
    public MessageBean<String> save(TeamHandover bean, TeamHandoverRelation relation, StaffBean user, MultipartFile[] files, String keepFile, String delFile) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", String.class);
        List<String> keepList = new ArrayList<>();
        List<String> keepPDFList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(bean.getHandoverCode()) || StringUtils.isEmpty(bean.getHandoverName())) {
                msg.setCode(BusinessCode.HANDOVER_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.HANDOVER_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getReceiverCode()) || StringUtils.isEmpty(bean.getReceiverName())) {
                msg.setCode(BusinessCode.RECEIVER_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.RECEIVER_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getDutyTeamName())) {
                msg.setCode(BusinessCode.DUTYTEAM_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.DUTYTEAM_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getDutyTeamUserCode()) || StringUtils.isEmpty(bean.getDutyTeamUserName())) {
                msg.setCode(BusinessCode.DUTYTEAMUSER_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.DUTYTEAMUSER_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isNotEmpty(keepFile)) {
                List<String> list = JSONObject.parseArray(keepFile, String.class);
                keepList.addAll(list);
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {//文件上传
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                    File pdfFile = docConverterUtils.converter(file);
                    if (pdfFile != null) {
                        String pdfFilePath = clientWrapper.uploadFile(new FileInputStream(pdfFile), pdfFile.length(), FilenameUtils.getExtension(pdfFile.getName()));
                        keepPDFList.add(pdfFilePath);
                    } else {
                        keepPDFList.add(null);
                    }
                }
            }
            bean.setAttachment((null == keepList || keepList.size() <= 0) ? null : new Gson().toJson(keepList));
            bean.setPreviewAttachment((null == keepPDFList || keepPDFList.size() <= 0) ? null : new Gson().toJson(keepPDFList));
            if (bean.getDeviceState() == 1) { // 设备异常
                if (StringUtils.isEmpty(bean.getHandoverExplain())) {//设备异常时，说明不能为空
                    msg.setCode(BusinessCode.HANDOVEREXPLAIN_NOT_EMPTY.getCode());
                    msg.setDescription(BusinessCode.HANDOVEREXPLAIN_NOT_EMPTY.getDescription());
                    return msg;
                }
//                if (null == relation.getHiddenDangerList() || relation.getHiddenDangerList().size() == 0) {//设备异常时，隐患整改不能为空
//                    msg.setCode(BusinessCode.HIDDENDANGERRECTIFICATION_NOT_EMPTY.getCode());
//                    msg.setDescription(BusinessCode.HIDDENDANGERRECTIFICATION_NOT_EMPTY.getDescription());
//                    return msg;
//                }
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getId())) {
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                value = factory.getMapper(TeamHandoverMapper.class).insert(bean);
                if (null != relation.getHiddenDangerList() && relation.getHiddenDangerList().size() > 0) {
                    msg = setData(bean, relation, user, msg, factory);
                }
                if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                    if (bean.getStatus() == 1) {
                        return getStringMessageBean(bean, relation, user, msg, factory);
                    } else if (bean.getStatus() == 0) {
                        factory.close();
                        msg.setData(bean.getId());
                        return msg;
                    }
                } else {
                    return msg;
                }
            } else {
                //修改
                TeamHandover entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.TEAMHANDOVE_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.TEAMHANDOVE_NOT_EXIST.getDescription());
                    return msg;
                } else if (entity.getStatus() != 0) {
                    msg.setCode(BusinessCode.NON_DRAFT_CANNOT_EDIT.getCode());
                    msg.setDescription(BusinessCode.NON_DRAFT_CANNOT_EDIT.getDescription());
                    return msg;
                }
                factory.getMapper(TeamHandoverMapper.class).update(bean);
                List<DeviceHiddenDanger> hiddenDangerList = relation.getHiddenDangerList();
                if (null != hiddenDangerList && hiddenDangerList.size() > 0) {
                    msg = setData(bean, relation, user, msg, factory);
                }
                if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                    if (bean.getStatus() == 1) {
                        return getStringMessageBean(bean, relation, user, msg, factory);
                    } else {
                        factory.close();
                        msg.setData(bean.getId());
                        return msg;
                    }
                } else {
                    return msg;
                }
            }
            if (value < 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
            }
            msg.setData(bean.getId());
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (StringUtils.isNotEmpty(delFile)) {
                List<String> list = JSONObject.parseArray(delFile, String.class);
                list.forEach(url -> clientWrapper.deleteFile(url.split("#")[0]));
            }
            if (null != factory) {
                factory.close();
            }
        }
    }

    public MessageBean<String> getStringMessageBean(TeamHandover bean, TeamHandoverRelation relation, StaffBean user, MessageBean<String> msg, SessionFactory factory) throws InvalidSystemClockException, GetHardwareIdFailedException {
        if (bean.getDeviceState() == 1 && (null == relation.getHiddenDangerList() || relation.getHiddenDangerList().size() == 0)) {
            Integer count = factory.getMapper(HiddenDangerMapper.class).countDangerByCheckRecordId(bean.getId());
            if (count <= 0) {
                msg.setCode(BusinessCode.HIDDENDANGERRECTIFICATION_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.HIDDENDANGERRECTIFICATION_NOT_EMPTY.getDescription());
                return msg;
            }
        }
        return auditSet(bean, user, msg, factory);
    }

    private MessageBean<String> setData(TeamHandover bean, TeamHandoverRelation relation, StaffBean user, MessageBean<String> msg, SessionFactory factory) throws IOException {
        List<String> attachmentList = new ArrayList<>();
        List<String> collectList = new ArrayList<>();
        List<DeviceHiddenDanger> hiddenDangerList = relation.getHiddenDangerList();
        if (hiddenDangerList != null && !hiddenDangerList.isEmpty()) {
            boolean result = true;
            for (int i = 0; i < hiddenDangerList.size(); i++) {
                DeviceHiddenDanger danger = hiddenDangerList.get(i);
                danger.setDerivation(4);
                List<String> newAtts = new ArrayList<>();
                List<MultipartFile> files = danger.getFiles();
                if (null != files && !files.isEmpty()) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        newAtts.add(url + "#" + file.getOriginalFilename());
                    }
                }
                try {
                    result = process(factory, user, danger, newAtts, bean.getId());
                    attachmentList.addAll(newAtts);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    result = false;
                }
                if (!result) {
                    //处理隐患失败即退出循环
                    break;
                }
            }
            if (!result) {
                removeAttachment(attachmentList);
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
            collectList = hiddenDangerList.stream().map(DeviceHiddenDanger::getId).collect(Collectors.toList());
            try {
                relation.setId(DefaultIdGenerator.getInstance().generateLongId());
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            relation.setTeamHandoverId(bean.getId());
            relation.setHiddenDangerIds(new Gson().toJson(collectList));
        }
        TeamHandoverMapper mapper = factory.getMapper(TeamHandoverMapper.class);
        TeamHandoverRelation other = mapper.queryRelation(relation.getTeamHandoverId());
        if (other == null) {
            mapper.batchInsertRelation(new ArrayList() {{
                add(relation);
            }});
        } else {
            List<String> ids = JSONObject.parseArray(other.getHiddenDangerIds(), String.class);
            List<String> finalCollectList = collectList;
            // 获取修改删除的隐患
            List<String> list = ids.stream().filter(id -> !finalCollectList.contains(id)).collect(Collectors.toList());
            if (null != list && list.size() > 0) {
                for (String s : list) {
                    // 获取隐患整改信息
                    List<HiddenDangerRectification> hiddenDangerRectifications = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(s);
                    if (null != hiddenDangerRectifications && hiddenDangerRectifications.size() > 0) {
                        List<String> collect = hiddenDangerRectifications.stream().map(hiddenDangerRectification -> hiddenDangerRectification.getId()).collect(Collectors.toList());
                        // 删除隐患整改记录
                        factory.getMapper(TeamHandoverMapper.class).batchDeleteHiddenDangerRectification(collect);
                    }
                }
                // 删除修改删掉的隐患记录
                factory.getMapper(HiddenDangerMapper.class).batchDeleteDanger(list);
            }
            relation.setId(other.getId());
            mapper.updateRelation(relation);
        }
        return msg;
    }

    private boolean process(SessionFactory factory, StaffBean user, DeviceHiddenDanger dangerDiscovery, List<String> newAtts, String id) throws GetHardwareIdFailedException, InvalidSystemClockException {
        dangerDiscovery.setCheckRecordId(id);
        dangerDiscovery.setUpdateUser(user.getName());
        dangerDiscovery.setUpdateTime(new Date());
        dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
        if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
            String[] arrays = dangerDiscovery.getInnerStaff().split("[,，]");
            dangerDiscovery.setInnerStaff(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
            String[] arrays = dangerDiscovery.getDiscovererCode().split("[,，]");
            dangerDiscovery.setDiscovererCode(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
            String[] arrays = dangerDiscovery.getDiscovererDepartment().split("[,，]");
            dangerDiscovery.setDiscovererDepartment(new Gson().toJson(Arrays.asList(arrays)));
        }
        //草稿
        dangerDiscovery.setState(7);
        if (StringUtils.isEmpty(dangerDiscovery.getCheckUnit()) && StringUtils.isEmpty(dangerDiscovery.getCheckUnitName())) {
            MessageBean<?> corpMsg = util.corp(user.getCode());
            if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                dangerDiscovery.setCheckUnitName(corp.getName());
            }
        }
        IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
        if (StringUtils.isEmpty(dangerDiscovery.getId())) {
            //新增操作
            dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
            dangerDiscovery.setCode(hiddenDangerService.generateCode(factory, dangerDiscovery));
            dangerDiscovery.setAddTime(dangerDiscovery.getUpdateTime());
            dangerDiscovery.setAddUser(dangerDiscovery.getUpdateUser());
            Port port = hiddenDangerService.getPort();
            List<DeptBean> departmentTreeBeanList = port.dept(user == null ? "1c6646fffe514a4c9539ba05fd3d92eb" : user.getCode()).getData();
            dangerDiscovery.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());
            if (null != newAtts && newAtts.size() > 0) {
                dangerDiscovery.setAttachment(new Gson().toJson(newAtts));
            }
            factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
            //构建隐患整改记录，填充整改人、整改期限、验证人、确认人、整改措施等信息
            HiddenDangerRectification rectification = new HiddenDangerRectification();
            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
            rectification.setConfirmPerson(dangerDiscovery.getConfirmPerson());
            rectification.setConfirmPersonName(dangerDiscovery.getConfirmPersonName());
            rectification.setRectifier(dangerDiscovery.getRectifier());
            rectification.setRectifierName(dangerDiscovery.getRectifierName());
            rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
            rectification.setReviewerName(dangerDiscovery.getReviewerName());
            rectification.setAddUser(dangerDiscovery.getAddUser());
            rectification.setAddUserName(dangerDiscovery.getAddUserName());
            rectification.setAddTime(dangerDiscovery.getAddTime());
            rectification.setUpdateUser(dangerDiscovery.getUpdateUser());
            rectification.setUpdateUserName(dangerDiscovery.getUpdateUserName());
            rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
            rectification.setDeadline(dangerDiscovery.getDeadline());
            rectification.setSolution(dangerDiscovery.getSolution());
            rectification.setHiddenDangerId(dangerDiscovery.getId());
            rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
            rectification.setDelayState(0);
            factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
            return true;
        } else {
            List<String> keepAttsList = new ArrayList<>();
            keepAttsList.addAll(newAtts);
            if (StringUtils.isNotEmpty(dangerDiscovery.getKeepAtts())) {
                String[] keepAttsArray = dangerDiscovery.getKeepAtts().split("[;；]");
                keepAttsList.addAll(Arrays.asList(keepAttsArray));
            }
            if (keepAttsList.size() > 0) {
                dangerDiscovery.setAttachment(new Gson().toJson(keepAttsList));
            }
            if (factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery) > 0) {
                if (StringUtils.isNotEmpty(dangerDiscovery.getDelAtts())) {
                    String[] delAttsArray = dangerDiscovery.getDelAtts().split("[;；]");
                    for (String att : delAttsArray) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
                HiddenDangerRectification rectification = new HiddenDangerRectification();
                rectification.setConfirmPerson(dangerDiscovery.getConfirmPerson());
                rectification.setConfirmPersonName(dangerDiscovery.getConfirmPersonName());
                rectification.setRectifier(dangerDiscovery.getRectifier());
                rectification.setRectifierName(dangerDiscovery.getRectifierName());
                rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                rectification.setReviewerName(dangerDiscovery.getReviewerName());
                rectification.setAddUser(dangerDiscovery.getAddUser());
                rectification.setAddUserName(dangerDiscovery.getAddUserName());
                rectification.setAddTime(dangerDiscovery.getAddTime());
                rectification.setUpdateUser(dangerDiscovery.getUpdateUser());
                rectification.setUpdateUserName(dangerDiscovery.getUpdateUserName());
                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                rectification.setDeadline(dangerDiscovery.getDeadline());
                rectification.setSolution(dangerDiscovery.getSolution());
                rectification.setHiddenDangerId(dangerDiscovery.getId());
                rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
                rectification.setDelayState(0);
                //判断是否填写了隐患整改信息
                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                if (null == rectificationList || rectificationList.size() <= 0) {
                    rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                    factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
                    return true;
                } else {
                    for (HiddenDangerRectification hiddenDangerRectification : rectificationList) {
                        rectification.setId(hiddenDangerRectification.getId());
                        factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                    }
                    return true;
                }
            }
            return false;
        }
    }

    private void removeAttachment(List<String> attachmentList) {
        if (null != attachmentList && attachmentList.size() > 0) {
            for (String att : attachmentList) {
                try {
                    clientWrapper.deleteFile(att.split("#")[0]);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
    }

    /**
     * 班组交接流程
     *
     * @param bean
     * @param user
     * @param msg
     * @param factory
     * @return
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    private MessageBean<String> auditSet(TeamHandover bean, StaffBean user, MessageBean<String> msg, SessionFactory factory) throws InvalidSystemClockException, GetHardwareIdFailedException {
        //启动流程
        Audit audit = new Audit();
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        audit.setUpdateUser(bean.getUpdateUserName());
        audit.setUpdateTime(bean.getUpdateTime());
        audit.setAddUser(bean.getUpdateUserName());
        audit.setAddTime(bean.getUpdateTime());
        audit.setFlowType(1);
        audit.setOperation(1);
        audit.setTarget(TeamHandoverServiceImpl.class.getName());
        audit.setFlowName("班组交接待审核");
        audit.setTitle("班组交接待审核");
        audit.setCorpCode(bean.getCorpCode());
        audit.setInitiatorCode(user.getCode());
        audit.setDescription("新增班组交接审核");
        audit.setState(1);
        audit.setTemplateKey("team_handover");
        audit.setSetCode("safe_scene");
        audit.setInitiatorAccount(user.getUserid());
        audit.setBusinessIds(bean.getId());
        List<String> idList = new ArrayList<>();
        idList.add(bean.getId());
        audit.setBusinessIds(new Gson().toJson(idList));
        Map<String, Object> businessMap = new HashMap<>();
        String receiver = bean.getReceiverCode().split("_")[1];
        businessMap.put("approver", receiver);
        if (!flowManagement.initFlow(user, audit, businessMap)) {
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("保存失败");
            return msg;
        } else {
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("保存成功");
            msg.setData(bean.getId());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> delete(String id, StaffBean user) {
        SessionFactory factory = new SessionFactory();
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try {
            TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(id);
            if (StringUtils.isEmpty(id) || null == teamHandover) {
                msg.setCode(BusinessCode.TEAMHANDOVE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.TEAMHANDOVE_NOT_EXIST.getDescription());
                return msg;
            }
            if (teamHandover.getStatus() != 0) {
                msg.setCode(BusinessCode.NON_DRAFT_CANNOT_DELETE.getCode());
                msg.setDescription(BusinessCode.NON_DRAFT_CANNOT_DELETE.getDescription());
                return msg;
            }
            Integer delete = factory.getMapper(TeamHandoverMapper.class).delete(id);
            if (delete <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
            TeamHandoverRelation relation = factory.getMapper(TeamHandoverMapper.class).queryRelation(id);
            if (null != relation) {
                // 获取隐患记录id
                String hiddenDangerIds = relation.getHiddenDangerIds();
                if (!StringUtils.isEmpty(hiddenDangerIds)) { //隐患记录id不为空时，对隐患记录信息和隐患整改信息进行操作
                    List<String> hiddenDangerIdList = JSONObject.parseArray(hiddenDangerIds, String.class);
                    for (String s : hiddenDangerIdList) {
                        // 获取隐患整改信息
                        List<HiddenDangerRectification> hiddenDangerRectifications = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(s);
                        if (null != hiddenDangerRectifications && hiddenDangerRectifications.size() > 0) {
                            List<String> collect = hiddenDangerRectifications.stream().map(hiddenDangerRectification -> hiddenDangerRectification.getId()).collect(Collectors.toList());
                            // 删除隐患整改记录
                            factory.getMapper(TeamHandoverMapper.class).batchDeleteHiddenDangerRectification(collect);
                        }
                    }
                    // 删除隐患记录
                    factory.getMapper(HiddenDangerMapper.class).batchDeleteDanger(hiddenDangerIdList);
                }
                factory.getMapper(TeamHandoverMapper.class).deleteRelationByTeamHandoverId(id);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("删除失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<TeamHandover> queryOne(String id) {
        SessionFactory factory = new SessionFactory();
        MessageBean<TeamHandover> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询成功", TeamHandover.class);
        try {
            TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(id);
            if (StringUtils.isEmpty(id) || null == teamHandover) {
                msg.setCode(BusinessCode.TEAMHANDOVE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.TEAMHANDOVE_NOT_EXIST.getDescription());
                return msg;
            }
            // 获取所有的隐患id
            TeamHandoverRelation relation = factory.getMapper(TeamHandoverMapper.class).queryRelation(id);
            List<HiddenDangerDiscovery> list = new ArrayList<>();
            if (null != relation) {
                String hiddenDangerIds = relation.getHiddenDangerIds();
                List<String> hiddenDangerIdList = JSONObject.parseArray(hiddenDangerIds, String.class);
                // 根据隐患id查询具体信息
                for (String hiddenDangerId : hiddenDangerIdList) {
                    HiddenDangerDiscovery data = dangerDiscoveryService.queryDangerOne(hiddenDangerId).getData();
                    list.add(data);
                }
            } else {
                HiddenDangerMapper hiddenDangerMapper = factory.getMapper(HiddenDangerMapper.class);
                List<String> hiddenDangerIdList = hiddenDangerMapper.getIdByCheckRecordId(id);
                hiddenDangerIdList.forEach(hiddenDangerId -> {
                    HiddenDangerDiscovery data = dangerDiscoveryService.queryDangerOne(hiddenDangerId).getData();
                    list.add(data);
                });
            }
            teamHandover.setHiddenDangerDiscoveryList(list);
            msg.setData(teamHandover);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<DataBean<TeamHandover>> list(String corpCode, String dutyTeamName, Integer start, Integer rows, String keyword) {
        MessageBean<DataBean<TeamHandover>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<TeamHandover> list = factory.getMapper(TeamHandoverMapper.class).queryByCondition(corpCode, dutyTeamName, start, rows, keyword);
            rows = (rows == null || rows <= 0) ? 1 : rows;
            Integer totalNumber = factory.getMapper(TeamHandoverMapper.class).countByCondition(corpCode, dutyTeamName, keyword);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<TeamHandover> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询班组交接列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List<TeamHandover>> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    for (String id : idList) {
                        TeamHandoverMapper mapper = factory.getMapper(TeamHandoverMapper.class);
                        TeamHandover teamHandover = mapper.queryById(id);
                        // 获取所有的隐患id
                        TeamHandoverRelation relation = factory.getMapper(TeamHandoverMapper.class).queryRelation(id);
                        if (null != relation) {
                            String hiddenDangerIds = relation.getHiddenDangerIds();
                            List<String> hiddenDangerIdList = JSONObject.parseArray(hiddenDangerIds, String.class);
                            List<HiddenDangerDiscovery> list = new ArrayList<>();
                            // 根据隐患id查询具体信息
                            for (String hiddenDangerId : hiddenDangerIdList) {
                                HiddenDangerDiscovery data = dangerDiscoveryService.queryDangerOne(hiddenDangerId).getData();
                                list.add(data);
                            }
                            teamHandover.setHiddenDangerDiscoveryList(list);
                        }
                        List<TeamHandover> teamHandoverList = new ArrayList<>();
                        teamHandoverList.add(teamHandover);
                        msg.setData(teamHandoverList);
                    }
                }
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("id不能为空");
            }
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public List<TeamHandover> export(StaffBean user, String corpCode, String dutyTeamName) {
        try (SessionFactory factory = new SessionFactory()) {
            List<TeamHandover> list = factory.getMapper(TeamHandoverMapper.class).queryByCondition(corpCode, dutyTeamName, null, null, null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                list.forEach(bean -> {
                    if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (null != bean.getAddTime()) {
                        bean.setDutyTimeStr(sdf.format(bean.getDutyTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> getHiddenDangers(String id, Integer page, Integer pageSize) {
        SessionFactory factory = new SessionFactory();
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询成功", DataBean.class);
        DataBean<HiddenDangerDiscovery>dataBean = new DataBean<>();
        try {

            TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(id);
            if (StringUtils.isEmpty(id) || null == teamHandover) {
                msg.setCode(BusinessCode.TEAMHANDOVE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.TEAMHANDOVE_NOT_EXIST.getDescription());
                return msg;
            }
            // 获取所有的隐患
            List<HiddenDangerDiscovery> hiddenDangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(id, null, null);
            Integer total = hiddenDangerDiscoveries.size();
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(total > pageSize ? (total % pageSize == 0 ? total / pageSize : total / pageSize + 1) : 1);
            Integer start = null;
            Integer end = null;
            if (null != page && pageSize != null) {
                if (page > 0 && pageSize > 0) {
                    start = (page <= 1) ? 0 : (page - 1) * pageSize;
                    end = page * pageSize;
                }
                if (start != null && end != null) { //需要分页
                    if (end > total) {
                        end = total;
                        if (start > end) {
                            start = end;
                        }
                    }
                }
            }
            dataBean.setList(hiddenDangerDiscoveries.subList(start, end));
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }

    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String id = idList.get(0);
                if (StringUtils.isNotEmpty(id)) {
                    TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(id);
                    if (null != teamHandover) {
                        //审核通过后，将状态设为2
                        teamHandover.setStatus(2);
                        factory.getMapper(TeamHandoverMapper.class).update(teamHandover);
                        // 班组交接通过后，启动隐患相关流程
                        setHiddenDanger(factory, id, teamHandover);
                    }
                }
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        }
    }

    /**
     * 班组交接完成后，启动隐患相关流程
     *
     * @param factory
     * @param id
     * @param teamHandover
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    private void setHiddenDanger(SessionFactory factory, String id, TeamHandover teamHandover) {
        try {
            String receiverCode = teamHandover.getReceiverCode().split("_")[0];
            StaffBean user = (StaffBean) discoveryService.getPort().staff(receiverCode, null).getData().get(0);
            // 获取所有的隐患id
            TeamHandoverRelation relation = factory.getMapper(TeamHandoverMapper.class).queryRelation(id);
            List<HiddenDangerDiscovery> dangers = new ArrayList<>();
            if (null != relation) {
                String hiddenDangerIds = relation.getHiddenDangerIds();
                List<String> hiddenDangerIdList = JSONObject.parseArray(hiddenDangerIds, String.class);
                // 根据隐患id查询具体信息
                for (String hiddenDangerId : hiddenDangerIdList) {
                    HiddenDangerDiscovery data = dangerDiscoveryService.queryDangerOne(hiddenDangerId).getData();
                    dangers.add(data);
                }
            } else {
                HiddenDangerMapper hiddenDangerMapper = factory.getMapper(HiddenDangerMapper.class);
                List<String> hiddenDangerIdList = hiddenDangerMapper.getIdByCheckRecordId(id);
                hiddenDangerIdList.forEach(hiddenDangerId -> {
                    HiddenDangerDiscovery data = dangerDiscoveryService.queryDangerOne(hiddenDangerId).getData();
                    dangers.add(data);
                });
            }
            // 班组交接审批完成后，自动启动隐患整改流程
            if (null != dangers && dangers.size() > 0) {
                // 获取隐患负责人
                Set<String> codeLists = dangers.stream().map(bean -> bean.getDangerManager().split("_")[0]).collect(Collectors.toSet());
                List<String> noticeCodeList = new ArrayList<>();
                for (String code : codeLists) {
                    try (SessionFactory sessionFactory = new SessionFactory()) {
                        // 同一个隐患负责人，提交成一条隐患流程
                        List<HiddenDangerDiscovery> discoveryList = dangers.stream().filter(bean -> code.equals(bean.getDangerManager().split("_")[0])).collect(Collectors.toList());
                        //整理隐患整改记录
                        HiddenDangerMapper mapper = sessionFactory.getMapper(HiddenDangerMapper.class);
                        List<HiddenDangerRectification> rectificationList = new ArrayList<>();
                        List<HiddenDangerRectification> deleteList = new ArrayList<>();
                        List<String> approvalList = new ArrayList<>();
                        for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                            //查询提交的隐患是不是已经有了整改记录；
                            List<HiddenDangerRectification> rectificationList1 = sessionFactory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                            //删除之前有的整改记录信息
                            if (rectificationList1 != null && rectificationList1.size() > 0) {
                                deleteList.addAll(rectificationList1);
                            }
                            //保存隐患整改信息，主要是配置隐患整改信息的验证人
                            HiddenDangerRectification rectification = new HiddenDangerRectification();
                            //保存整改信息
                            rectification.setHiddenDangerId(dangerDiscovery.getId());
                            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                            rectification.setAddTime(dangerDiscovery.getUpdateTime());
                            rectification.setAddUser(user.getName());
                            rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                            rectification.setUpdateUser(user.getName());
                            rectification.setRectifier(dangerDiscovery.getDangerManager());
                            rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                            rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                            rectification.setSolution(dangerDiscovery.getDescription());
                            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
                            if (!approvalList.contains(staffBeanList.get(0).getUserid())) {
                                approvalList.add(staffBeanList.get(0).getUserid());
                            }
                            rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                            rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                            rectification.setDelayState(0);
                            IndicationItems items = sessionFactory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                            rectification.setRectificationState(items == null ? null : items.getId());
                            rectificationList.add(rectification);
                        }
                        //更新选中的隐患为确认状态；启动隐患流程
                        List<String> ids = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                        mapper.updateDangerState(2, ids);
                        try {
                            for (HiddenDangerDiscovery discovery : discoveryList) {
                                List<Message> messages = new ArrayList<>();
                                if (discovery.getCopyPerson() != null) {
                                    String[] copyPersons = discovery.getCopyPerson().split(",");
                                    for (String copyPerson : copyPersons) {
                                        Message message = new Message();
                                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                        message.setTitle("有一项您关注的隐患整改");
                                        message.setIsRead(0);
                                        message.setIsRemove(0);
                                        message.setAddTime(new Date());
                                        message.setAddUser(discovery.getAddUser());
                                        message.setContent("隐患描述：" + discovery.getDescription());
                                        message.setReceiverCode(copyPerson.split("_")[0]);
                                        messages.add(message);
                                    }
                                }
                                if (messages != null && messages.size() > 0) {
                                    factory.getMapper(MessageMapper.class).batchInsert(messages);
                                }
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                        }
                        mapper.batchInsertRectification(rectificationList);
                        if (deleteList != null && deleteList.size() > 0) {
                            List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                            mapper.bateDeleteRectification(deleteIdList);
                        }
                        Date date = new Date();
                        Audit auditBean = new Audit();
                        auditBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                        auditBean.setUpdateUser(user.getName());
                        auditBean.setUpdateTime(date);
                        auditBean.setAddTime(date);
                        auditBean.setAddUser(user.getName());
                        auditBean.setFlowType(2);
                        auditBean.setOperation(1);
                        auditBean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                        auditBean.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                        auditBean.setNowNodeCode("Process-task2");
                        auditBean.setTitle("隐患整改流程");
                        auditBean.setCorpCode(discoveryList.get(0).getCorpCode());
                        auditBean.setBusinessIds(new Gson().toJson(ids));
                        auditBean.setInitiatorCode(user.getCode());
                        auditBean.setTemplateKey(hiddenDangerWorkFlow);
                        auditBean.setInitiatorAccount(user.getUserid());
                        auditBean.setSetCode(riskDangerSetCode);
                        auditBean.setDescription("隐患整改流程");
                        auditBean.setState(1);
                        Map<String, Object> businessDataMap = new HashMap<>();
                        String userid = approvalList.stream().collect(Collectors.joining(","));
                        businessDataMap.put("rectifier", userid);
                        businessDataMap.put("reviewer", userid);
                        businessDataMap.put("verification", user.getUserid());
                        if (!flowManagement.initFlow(user, auditBean, businessDataMap)) {
                            // 如果自动提交隐患失败，将隐患修改为草稿，可在隐患台账处提交
                            factory.getMapper(HiddenDangerMapper.class).updateDangerState(0, ids);
                            sessionFactory.close(false);
                        } else {
                            // 提交成功，生成整改通知书
                            String noticeCode = HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(sessionFactory, user, discoveryList);
                            if (StringUtils.isNotEmpty(noticeCode)) {
                                noticeCodeList.add(noticeCode);
                            }
                            sessionFactory.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String teamHandoverId = idList.get(0);
                if (StringUtils.isNotEmpty(teamHandoverId)) {
                    TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(teamHandoverId);
                    if (teamHandover != null) {
                        //删除通过后，更新状态
                        teamHandover.setStatus(2);
                        factory.getMapper(TeamHandoverMapper.class).update(teamHandover);
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String id = idList.get(0);
                if (StringUtils.isNotEmpty(id)) {
                    TeamHandover teamHandover = factory.getMapper(TeamHandoverMapper.class).queryById(id);
                    if (teamHandover != null && teamHandover.getStatus() == 1) {
                        //新增审核不通过后，将状态设为0.草稿
                        teamHandover.setStatus(0);
                        factory.getMapper(TeamHandoverMapper.class).update(teamHandover);
                    }
                    List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(id, null, null);
                    if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                        for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                            dangerDiscovery.setState(0);
                        }
                        factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangerDiscoveryList);
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(TeamHandoverServiceImpl.class.getName(), this);
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
